<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-alert title="添加商品信息" type="info" center show-icon> </el-alert>

      <!-- 步骤条 -->
      <el-steps
        :space="200"
        :active="activeIndex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- 表单 -->
      <el-form
        :model="infoForm"
        :rules="infoFormRules"
        ref="infoFormRef"
        label-width="100px"
        label-position="top"
      >
        <!-- 标签页 -->
        <el-tabs
          tab-position="left"
          :before-leave="beforeLeave"
          @tab-click="clickTab"
        >
          <!-- 基本信息标签 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item prop="goods_name" label="商品名称">
              <el-input v-model="infoForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item prop="goods_price" label="商品价格">
              <el-input v-model="infoForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item prop="goods_weight" label="商品重量">
              <el-input
                v-model="infoForm.goods_weight"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item prop="goods_number" label="商品数量">
              <el-input v-model="infoForm.goods_number" type="number">
              </el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <template>
                <!-- 级联选择器 -->
                <el-cascader
                  v-model="infoForm.goods_cat"
                  :options="catesList"
                  :props="props"
                  @change="handleChange"
                ></el-cascader>
              </template>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品参数标签 -->
          <el-tab-pane label="商品参数" name="1">
            <!-- 遍历参数列表 -->
            <el-form-item
              v-for="item in manyTableDate"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <!-- 遍历attr_vals -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  v-for="(item1, i) in item.attr_vals"
                  :key="i"
                  :label="item1"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>

          <!-- 商品属性标签 -->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              v-for="item in onlyTableDate"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>

          <!-- 商品图片标签 -->
          <el-tab-pane label="商品图片" name="3">
            <!-- 上传图片 -->
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headersObj"
              :on-success="handlerSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>

          <!-- 商品内容标签 -->
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本 -->
            <quill-editor v-model="infoForm.goods_introduce"></quill-editor>

            <!-- 添加商品按钮 -->
            <el-button type="primary" class="addBtn" @click="addGoods"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 预览图片 -->
    <el-dialog title="提示" :visible.sync="preDialogVisible" width="50%">
      <img :src="previewImg" alt="" style="width: 100%" />
    </el-dialog>
  </div>
</template>

<script>
import _ from "lodash";

export default {
  name: "Add",
  data() {
    return {
      // 当前激活的步骤
      activeIndex: 0,
      // 基本信息
      infoForm: {
        goods_name: "",
        goods_price: 1,
        goods_weight: 1,
        goods_number: 1,
        // 临时路径
        pics: [],
        // 以为','分割的分类列表
        goods_cat: [1, 3, 6],
        // 静态动态数字列表
        attrs: [],
        // 介绍
        goods_introduce: "",
      },
      infoFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
      },
      // 商品分类
      catesList: [],
      // 选中的数组

      props: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
      },

      // 商品参数
      manyTableDate: [],
      // 商品属性
      onlyTableDate: [],
      // 上传文件
      uploadURL: "http://127.0.0.1:8888/api/private/v1/upload",

      // 设置请求上传的头部
      headersObj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      // 预览图片
      preDialogVisible: false,
      previewImg: "",
    };
  },
  created() {
    this.getCatesList();
  },
  methods: {
    // 获取商品分类列表
    async getCatesList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) return this.$message.error("获取失败");

      this.catesList = res.data;
    },
    // 级联选择器发生改变
    handleChange() {
      this.cateId();
    },
    // 切换出标签页之前的钩子
    beforeLeave(activeName, oldActiveName) {
      // 切换出第一个标签之前的钩子
      // 必须选择三级商品分类
      if (oldActiveName === "0") {
        if (this.infoForm.goods_cat.length !== 3) {
          this.$message.error("请选择商品分类");
          return false;
        }
      }
      this.activeIndex = activeName;
    },

    // 点击标签页
    async clickTab() {
      // 点击商品参数标签
      if (this.activeIndex === "1") {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "many" },
          }
        );

        // 将字符串改为数组、
        res.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals.trim().length === 0 ? [] : item.attr_vals.split(" ");
        });
        this.manyTableDate = res.data;
      } else if (this.activeIndex === "2") {
        // 点击商品属性标签
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "only" },
          }
        );
        if (res.meta.status !== 200)
          return this.$message.error("获取商品属性失败");

        this.onlyTableDate = res.data;
      }
    },
    // 处理查看缩略图
    handlePreview(file) {
      this.previewImg = file.response.data.url;
      this.preDialogVisible = true;
    },
    // 处理删除图片
    handleRemove(file) {
      // 获取删除图片的临时路径
      const tmp_path = file.response.data.tmp_path;

      const i = this.infoForm.pics.findIndex((x) => x === tmp_path);

      this.infoForm.pics.splice(i, 1);
    },
    // 处理上传完成
    handlerSuccess(file) {
      const tmp_path = file.data.tmp_path;
      this.infoForm.pics.push(tmp_path);
    },
    // 添加商品
    addGoods() {
      this.$refs.infoFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error("请填写必填信息");

        // 将动态参数和静态属性添加到attrs
        this.manyTableDate.forEach((item) => {
          const obj = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(" "),
          };
          this.infoForm.attrs.push(obj);
        });
        // 将动态参数和静态属性添加到attrs
        this.onlyTableDate.forEach((item) => {
          const obj = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          };
          this.infoForm.attrs.push(obj);
        });

        const form = _.cloneDeep(this.infoForm);
        form.goods_cat = form.goods_cat.join(",");

        const { data: res } = await this.$http.post("goods", form);
        if (res.meta.status !== 201) return this.$message.error("创建失败");

        this.$message.success("创建成功");

        this.$router.push("/goods");
      });
    },
  },
  computed: {
    cateId() {
      if (this.infoForm.goods_cat.length === 3) {
        return this.infoForm.goods_cat[2];
      }
      return null;
    },
  },
};
</script>

<style scoped>
.el-steps {
  margin-top: 15px;
}
.el-step {
  flex: 1;
}
.addBtn {
  margin-top: 15px;
}
</style>